package com.mandao.concurrency.example.atomic;

import com.mandao.concurrency.annotations.ThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.LongAdder;

/**
 * 线程安全性:
 *  *   原子性:提供了互斥访问,同一时刻只能有一个线程来对它进行操作
 *  *   atomicLong: CAS  unsafe.compareAndSwapLong
 *  *   jdk1.8 新增了 LongAdder
 *
 * @author 蜗牛
 */
@Slf4j
@ThreadSafe
public class AtomicExample3 {
    //请求总数
    public static int clientTotal = 5000;
    //并发执行的线程
    public static int threadTotal = 200;
    //计数
    public static LongAdder count = new LongAdder();

    public static void main (String[] args) throws InterruptedException {
        //线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        //信号量
        final Semaphore semaphore = new Semaphore(threadTotal);
        //计数器
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        //
        for (int i = 0; i < clientTotal; i++) {
            executorService.execute(()->{
                try {
                    // 进源码看acquire方法的作用 判断当前线程是否可用
                    semaphore.acquire();
                    add();
                    // 是否当前线程
                    semaphore.release();
                } catch (InterruptedException e) {
                    log.info("exception",e);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        log.info("count:{}",count);
    }

    /**
     * 计数的方法
     */
    public static void add(){
        count.increment();
    }
}
